# -*- coding: utf-8 -*-
# @Time : 2023/7/30 5:10
# @Author : zxp
from django.contrib.auth.models import User
from rest_framework import serializers


class UserDetailSerializer(serializers.ModelSerializer):
    """用户信息显示"""

    class Meta:
        model = User
        fields = ['id', 'username', 'last_login', 'date_joined']  # 要显示的字段


class UserRegisterSerializer(serializers.ModelSerializer):
    # lookup_field:查找目标字段---username
    # 超链接如：xxxx/api/user/xxp/，xxp即为username（User模型中的字段）
    url = serializers.HyperlinkedIdentityField(view_name='user-detail', lookup_field='username')

    class Meta:
        model = User
        fields = ['url', 'id', 'username', 'password', 'is_superuser']
        extra_kwargs = {'password': {'write_only': True},
                        'is_superuser': {'read_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)  # 密码自动经过哈希加密
        return user

    def update(self, instance, validated_data):
        if 'password' in validated_data:  # 存在这个数据
            password = validated_data.pop('password')
            instance.set_password(password)  # 手动哈希加密
        return super().update(instance, validated_data)
